<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-09-17
 * Time: 14:37
 */

namespace App\Repositories;


use App\Models\AuctionGoodsInfo;
use App\Models\Goods;
use App\Models\GoodsCategory;
use App\Models\GoodsSku;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * Class GoodsRepository
 * @package App\Repositories
 */
class GoodsRepository extends BaseRepositories
{
    /**
     * @var Goods 注入的Goods model
     */
    protected $goods;

    /**
     * @var GoodsCategory
     */
    protected $goodsCategory;

    /**
     * @var AuctionGoodsInfo
     */
    protected $auctionGoodsInfo;

    /**
     * @var GoodsSku
     */
    protected $goodsSku;

    /**
     * 引入attachment操作
     * @var AttachmentRepository
     */
    protected $attachmentRepository;

    /**
     * GoodsRepository constructor.
     * @param Goods $goods
     */
    public function __construct(AttachmentRepository $attachmentRepository ,
                                Goods $goods, GoodsCategory $goodsCategory,
                                AuctionGoodsInfo $auctionGoodsInfo,
                                GoodsSku $goodsSku){
        $this->goods = $goods;
        $this->goodsCategory = $goodsCategory;
        $this->auctionGoodsInfo = $auctionGoodsInfo;
        $this->goodsSku = $goodsSku;
        $this->attachmentRepository = $attachmentRepository;
    }

    /**
     * 添加商品分类
     * @param array $data
     * @return mixed
     */
    public function addGoodsCategoryRepository(array $data){
        return $this->goodsCategory->create($data);
    }

    /**
     * 更新商品分类
     * @param array $data
     * @param int $categoryId
     * @return mixed
     */
    public function updateGoodsCategoryRepository(array $data, int $categoryId){

        //关联attachment
        if($this->attachmentRepository->bindBelongs($categoryId, MODEL_GOODS_CATEGORY, $data['pic'])){

            //更新分类
            return $this->goodsCategory->where('categoryId', $categoryId)->update($data);
        }
        return false;

    }

    /**
     * 删除商品分类
     * @param int $categoryId
     * @return mixed
     */
    public function deleteGoodsCategoryRepository(int $categoryId){
        return $this->goodsCategory->where('categoryId', $categoryId)->delete();
    }

    /**
     * 分类下是否含有商品
     * @param int $categoryId
     * @return mixed
     */
    public function checkHasGoodsInGoodsCategory(int $categoryId){
        return $this->goods->where('categoryId', $categoryId)->exists();
    }

    /**
     * 获取分类信息详情
     * @param $categoryId
     * @return mixed
     */
    public function goodsCategoryDetail($categoryId){
        return $this->goodsCategory->findOrFail($categoryId);
    }

    /**
     * 更新推荐状态
     * @param array $data
     * @return mixed
     */
    public function updateRecommendGoodsCategoryRepository(array $data){
        return $this->goodsCategory
            ->where('categoryId', $data['categoryId'])
            ->update(['status'=>$data['status'],
                'updateTime'=>Carbon::now()]);
    }

    /**
     * 获取商品分类分页列表
     * @param int $limit
     * @param array $data
     * @return mixed
     */
    public function getCategoryPageRepository($limit = LIMIT_PAGE, array $data){
        return $this->goodsCategory
            ->withCount(['goods'])
            ->when($data, function ($q)use($data){
                $q->where($data);
            })
            ->orderBy('sort', 'asc')
            ->paginate($limit);
    }

    /**
     * @return mixed
     */
    public function goodsListRepository(){
        return $this->goodsCategory
            ->with(['children'])
            ->where('parentId', 0)
            ->get();
    }

    /**
     * 添加商品
     * @param array $data
     * @return Goods
     */
    public function addGoodsRepository(array $data){//var_dump($data);exit;

        DB::beginTransaction();
        try {

            //获取图片信息
            $headImage = [];
            foreach ($data['selectGroupPics'] as $groupPic){
                $headImage[] = $groupPic['id'];
            }

            $goodsData = [
                'createBy' => $data['createBy'],
                'categoryId'=>data_get($data, 'goodsCategoryId', 0),
                'goodsName'=>data_get($data, 'goodsName'),
                'goodsDetail'=>data_get($data, 'goodsDetail'),
                'status'=>data_get($data, 'status', 0),
                'soldNum'=>data_get($data, 'soldNum', 0),
                'viewCount'=>data_get($data, 'viewCount', 0),
                'reviewCount'=>data_get($data, 'reviewCount', 0),
                'rating'=>data_get($data, 'rating', 0),
                'headImage'=> \GuzzleHttp\json_encode($headImage),
                'goodsType'=>data_get($data, 'goodsType'),
                'priceType'=>data_get($data, 'goodsType'),
                'supplierId'=>data_get($data, 'supplierId', 0),
                'integral'=>data_get($data, 'integral', 0),
                'logo'=> data_get($data, 'logo'),
                'updateTime'=> Carbon::now(),
                'createTime'=> Carbon::now(),
            ];

            //保存商品信息
            $goodsId = $this->goods->insertGetId($goodsData);

            //保存sku信息
            if($goodsId){

                //关联attachment
                $this->attachmentRepository->bindBelongs($goodsId, MODEL_GOODS, $data['selectGroupPics']);
                $this->attachmentRepository->bindBelongs($goodsId, MODEL_GOODS, $data['logoPics']);

                //sku相关属性
                $skuData = [];
                if($sku = data_get($data, 'sku')){
                    foreach ($sku as $item){
                        $skuData[] = array_merge($item,
                            ['goodsId'=>$goodsId]
                        );
                    }
                    $skuData && $this->goodsSku->insert($skuData);
                }
            }

            DB::commit();
            return $this->goods;
        } catch (\Exception $e) {
            DB::rollback();
            $this->response->errorInternal('第'.$e->getCode().'行报错：'.$e->getMessage());exit;
        }
    }

    /**
     * 商品分页列表
     * @param array $data
     * @param int $limit
     * @return mixed
     */
    public function getGoodsPageRepository(array $data, int $limit = LIMIT_PAGE){
        return $this->goods
            ->with(['category'=>function($q){
                $q->select('name', 'categoryId');
            }])
            ->whereDoesntHave('auctionGoods')
            ->when($data, function ($q)use($data){
                $q->where($data);
            })
            ->orderByDesc('updateTime')
            ->paginate($limit);
    }

    /**
     * @param int $id
     * @return Goods|Goods[]|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model
     */
    public function getGoodsDetailRepository(int $id){
        return $this->goods
            ->whereDoesntHave('auctionGoods')
            ->findOrFail($id);
    }

    /**
     * @param $goodsId
     * @return mixed
     */
    public function getGoodsSkuRepository($goodsId,$keyword){
        return $this->goodsSku
            ->when($keyword, function ($q)use($keyword){
                $q->where('title', 'like', '%'.$keyword.'%')
                ->orWhere('description', 'like', '%'.$keyword.'%');
            })
            ->where('goodsId',$goodsId)
            ->get();
    }

    /**
     * 更新sku信息
     * @param $data
     * @return bool
     */
    public function updateGoodsSkuRepository($data){
        DB::beginTransaction();
        try {

            foreach ($data as $datum){
                data_set($datum, 'updated_at', Carbon::now());
                $this->goodsSku->where('id', $datum['id'])->update($datum);
            }

            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollback();
            $this->response->errorInternal($e->getMessage());exit;
        }
    }

    /**
     * 保存拍卖信息
     * @param array $data
     * @return AuctionGoodsInfo
     */
    public function addAuctionInfoRepository(array $data){

        //保存拍卖和sku信息
        $auctionInfo = [
            'goodsId'=>$data['goodsId'],
            'goodsSkuId' =>$data['goodsSkuId'],
            'assessPrice'=>data_get($data, 'assessPrice', 0),
            'costPrice'=>data_get($data, 'costPrice', 0),
            'startPrice'=>data_get($data, 'startPrice', 0),
            'brokerage'=>data_get($data, 'brokerage', 0),
            'integral'=>data_get($data, 'integral', 0),
            'markupPrice'=>data_get($data, 'markupPrice', 0),
            'displayArea'=>data_get($data, 'displayArea'),
            'status'=>data_get($data, 'status', 0),
            'startTime'=>data_get($data, 'startTime'),
            'endTime'=>data_get($data, 'endTime')
        ];

        //拍卖相关信息
        $this->auctionGoodsInfo->create($auctionInfo);

        return $this->auctionGoodsInfo;
    }

    /**
     * 获取所有商品总量
     * @return mixed
     */
    public function getGoodsCountRepository(){
        return $this->goods->count();
    }

    /**
     * 删除商品
     * @param array $ids
     * @return int
     */
    public function deleteGoodsRepository(array $ids){
        return $this->goods->destroy($ids);
    }

    /**
     * 更新状态及推荐
     * @param array $ids
     * @param array $data
     * @return mixed
     */
    public function updateGoodsStatusRepository(array $ids, array $data){
        return $this->goods
            ->whereIn('id', $ids)
            ->when(isset($data['status']), function ($q)use($data){
                $q->update(['status'=>$data['status']]);
            })
            ->when(isset($data['isRecommend']), function ($q)use($data){
                $q->update(['isRecommend'=>$data['isRecommend']]);
            });
    }
}
